package dao

import (
	"src/conf/database"
	"src/entity"
)

// InsertUserPurchase 将购买记录插入到数据库中，并返回错误信息
func InsertUserPurchase(purchase *entity.UserPurchase) error {
	// 使用已经初始化的单例数据库连接
	db := database.InitDatabase()

	if err := db.Create(purchase).Error; err != nil {
		return err
	}

	return nil
}

// SelectPurchaseListByWalletAddress 查询指定钱包地址的所有购买记录，并按购买时间降序排列
func SelectPurchaseListByWalletAddress(walletAddress string) ([]entity.UserPurchase, error) {
	// 使用已经初始化的单例数据库连接
	db := database.InitDatabase()

	var purchases []entity.UserPurchase
	if err := db.Where("wallet_address = ?", walletAddress).Order("purchase_time DESC").Find(&purchases).Error; err != nil {
		return nil, err
	}

	return purchases, nil
}

// SelectLastPurchaseByAddress 根据钱包地址查询最近一条购买记录
func SelectLastPurchaseByAddress(address string) (entity.UserPurchase, error) {
	// 使用已经初始化的单例数据库连接
	db := database.InitDatabase()

	var purchase entity.UserPurchase
	if err := db.Where("wallet_address = ?", address).Order("purchase_time DESC").Limit(1).Find(&purchase).Error; err != nil {
		return entity.UserPurchase{}, err
	}

	return purchase, nil
}

// SelectLastPurchaseById 查询指定用户ID的最近一条购买记录
func SelectLastPurchaseById(id int) (entity.UserPurchase, error) {
	// 使用已经初始化的单例数据库连接
	db := database.InitDatabase()

	var purchase entity.UserPurchase

	if err := db.Where("user_id = ?", id).Order("purchase_time DESC").Limit(1).Find(&purchase).Error; err != nil {
		return entity.UserPurchase{}, err
	}

	return purchase, nil
}
